<?php

namespace App\Models\Base;

use App\Models\BaseModel;
use App\Params\Backend\GroupUpdateParam;

/**
 * 系统分组模型类
 *
 * @package App\Models
 * @author WangBin
 * @date 2021-06-11
 */
class Group extends BaseModel
{
    protected $table = 'base_group';
    protected $primaryKey = 'group_id';

    /**
     * 获取对应类型的分组列表
     *
     * @param string $type
     * @return
     */
    public static function getList(string $type = '')
    {
        $query = Group::query();
        if($type) {
            $query->where('type', $type);
        }
        return $query;
    }

    /**
     * 获取对应类型的分组列表
     *
     * @param string $type
     * @return
     */
    public static function getForSelect(string $type = '')
    {
        $query = Group::query();
        if($type) {
            $query->where('type', $type);
        }
        return $query->get();
    }

    /**
     * 根据 Id 获取分组
     *
     * @param int $id
     * @return mixed
     */
    public static function getById(int $id)
    {
        return Group::find($id);
    }

    /**
     * 保存数据
     *
     * @param GroupUpdateParam $param
     * @return int|mixed
     */
    public static function saveData(GroupUpdateParam $param)
    {
        $query = $param->getGroupId() ? Group::find($param->getGroupId()) : new Group();
        foreach ($param as $field => $val)
        {
            $query->{$field} = $val;
        }
        return $query->save() ? $query->group_id : 0;
    }

    /**
     * 检查分组名唯一
     *
     * @param string $name
     * @param string $type
     * @param int $groupId
     * @return bool
     */
    public static function checkGroupName(string $name, string $type, int $groupId = 0)
    {
        $query = Group::query()->where('group_name', $name)->where('type', $type);
        if($groupId) {
            $query->where('group_id', '!=', $groupId);
        }
        return $query->exists();
    }

    /**
     * 批量删除
     *
     * @param array $ids
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public static function batchRemove(array $ids)
    {
        return Group::query()->whereIn('group_id', $ids);
    }
}
